# -*- coding: utf-8 -*-
# @Time : 2020/8/14 17:17
# @Author : yongf
# @File : ips.py
# @Software: PyCharm

from utils.Db import *


class ips:
    # 保存数据
    @staticmethod
    def save(self, ip, port, server_address, server_type, source=''):
        db = Db()

        types = server_type.split(',')
        type = 1
        if len(types) == 2:
            type = 3
        else:
            if 'HTTPS' in types:
                type = 2

        insert_sql = "insert into ips (ip,port,server_address,server_type,`type`,source,create_time) values ('%s','%d','%s','%s',%d,'%s','%s')" % (
            ip, port, server_address, server_type, type, source, now())

        res = False
        if db.insert(insert_sql):
            res = True

        db.close()
        return res

    # 删除数据
    @staticmethod
    def delete(self, ip, port):
        db = Db()
        sql = "delete from ips where ip='%s' and port=%d" % (ip, port)
        res = False
        if db.delete(sql):
            res = True

        db.close()
        return res

    # 获取单条数据
    @staticmethod
    def select(self, ip, port, fields='id,ip,port,server_type'):
        db = Db()
        sql = "select %s from ips where ip='%s' and port=%d" % (fields, ip, port)
        res = db.selectOne(sql)
        db.close()
        return res

    # 获取所有数据
    @staticmethod
    def selectAll(self, order='id desc', limit=0, offset=20, fields='id,ip,port,server_type'):
        db = Db()
        sql = "select %s  from ips order by %s limit %d,%d " % (fields, order, limit, offset)
        res = db.select(sql)
        db.close()
        return res

    # 获取条数
    @staticmethod
    def count(self):
        db = Db()
        sql = "select count(*) s_count from ips"
        res = db.selectOne(sql)
        db.close()
        if len(res) > 0:
            return res[0]
        return 0
